<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

	public $data;

	function __construct(){
		parent::__construct();
		if(!$this->auth->checkAdminLogin()) redirect('home/index');
	}

	public function index()
	{
		redirect('admin/home/history');
	}

	public function adduser(){
		$this->data['email'] = '';
		$this->data['uname'] = '';
		$this->data['group_id'] = '0';
		// Check submit
		if($this->input->post('save')){
			// Validate post data
			$this->load->library('form_validation');
			$this->form_validation->set_rules('email', 'Email', $this->validate->email());
			$this->form_validation->set_rules('uname', 'Họ tên', $this->validate->uname());

			$data['email'] = trim($this->input->post('email'));
			$data['uname'] = $this->input->post('uname');
			$data['group_id'] = intval($this->input->post('group_id'));
			// Validate
			if ($this->form_validation->run())
			{
				$data['password'] = MD5(PASS_DEFAULT);
				$data['update_date'] = date('Y-m-d H:i:s');
				// Get email and password from database
				$this->load->model('User_model');
				$user = $this->User_model->saveUser($data);
				// Check user exist
				if($user){
					$this->data['message'] = "Lưu ".$data['email']." thành công";
					// Set user name of current user
					if($data['email'] == $this->session->userdata('Email')){
						$this->auth->setSessionUserName($data['uname']);
						$this->auth->setSessionGroupId($data['group_id']);
					}
					// Send mail
					/*
					$address	= $data['email'];
					$from 		= MAIL_ADMIN;
					$subject	= 'Van Lang Uni - Thông tin giảng viên';
					$message	= 'Chào '.$data['uname'].' !';
					$message	+= 'Mật khẩu để vào trang '.base_url().' của bạn là : '.PASS_DEFAULT.'.';
					$this->sendMail($address, $from, $subject, $message);
					*/
				}else{// User not exist
					$this->data['message'] = "Xem lại lần nữa";
				}
			}else{
				$this->data = $data;
			}
		}

		if($this->input->post('cancel')){
			redirect('admin/home/index');
		}

		$this->template->write_view('content', 'admin/adduser',$this->data);
		$this->template->render();
	}

	public function history(){
		$this->load->model('Info_model');
		$data = $this->Info_model->getLastHistory();
		if($data){
			$this->data['listUser'] = $data;
		}else{
			$this->data['listUser'] = NULL;
		}

		$this->template->write_view('content', 'admin/history',$this->data);
		$this->template->render();
	}

	function sendMail($address, $from, $subject, $message){
		$this->load->library('email');
		$this->email->clear();

		$this->email->to($address);
		$this->email->from($from);
		$this->email->subject($subject);
		$this->email->message($message);
		$this->email->send();
	}
}